import { ApiHideProperty, ApiProperty } from '@nestjs/swagger'
import {
  Column,
  Entity,
  JoinColumn,
  ManyToOne,
  OneToMany,
  Relation,
  Tree,
  TreeChildren,
  TreeParent,
} from 'typeorm'

import { CompleteEntity } from '~/common/entity/common.entity'

import { UserEntity } from '../user/user.entity'

@Entity({ name: 'system_dept' })
@Tree('materialized-path')
export class DeptEntity extends CompleteEntity {
  @Column({ type: 'varchar', length: 30, comment: '部门名称' })
  @ApiProperty({ description: '部门名称' })
  name: string

  @Column({ name: 'parent_id', type: 'int', nullable: true, default: null, comment: '父部门id' })
  @ApiProperty({ description: '父部门id' })
  parentId: number

  @Column({ type: 'int', default: 0, comment: '显示顺序' })
  @ApiProperty({ description: '显示顺序' })
  sort: number

  @Column({ name: 'leader_user_id', type: 'int', nullable: true, comment: '负责人' })
  @ApiProperty({ description: '负责人' })
  leaderUserId: number

  @Column({ type: 'varchar', length: 11, nullable: true, comment: '联系电话' })
  @ApiProperty({ description: '联系电话' })
  phone: string

  @Column({ type: 'varchar', length: 50, nullable: true, comment: '邮箱' })
  @ApiProperty({ description: '邮箱' })
  email: string

  @Column({ type: 'tinyint', comment: '部门状态（0正常 1停用）' })
  @ApiProperty({ description: '部门状态（0正常 1停用）' })
  status: number

  @TreeChildren({ cascade: true })
  children: DeptEntity[]

  @TreeParent()
  parent?: DeptEntity

  @ApiHideProperty()
  @OneToMany(() => UserEntity, user => user.dept)
  users: Relation<UserEntity[]>

  @ManyToOne(() => UserEntity, { nullable: true })
  @JoinColumn({ name: 'leader_user_id' })
  @ApiProperty({ description: '负责人信息', type: () => UserEntity })
  leader?: UserEntity
}
